package com.hhf.rpa.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.Statement;

@Slf4j
@Component
public class DatabaseInitializer implements CommandLineRunner {
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    SqlSessionFactory sqlSessionFactory;

    private static final String initDdlPath = "classpath:static/sql/init_ddl.sql";
    private static final String initDmlPath = "classpath:static/sql/init_dml.sql";

    @Override
    public void run(String... args) throws Exception {
        String ddlSql = readSqlFile(initDdlPath);
        String dmlSql = readSqlFile(initDmlPath);

        try (Connection connection = sqlSessionFactory.openSession().getConnection();
             Statement statement = connection.createStatement()) {
            // 将整个SQL内容按分号分割成多个语句
            String[] ddlSqlStatements = ddlSql.split(";");
            String[] dmlSqlStatements = dmlSql.split("-- ");
            for (String sql : ddlSqlStatements) {
                if (!sql.trim().isEmpty()) {  // 去除空语句
                    statement.executeUpdate(sql);
                }
            }
            for (String sql : dmlSqlStatements) {
                if (!sql.trim().isEmpty()) {  // 去除空语句
                    statement.executeUpdate(sql);
                }
            }
        }
        log.info("数据库初始化完成");
        openBrowser();
    }

    /**
     * 服务启动后直接打开浏览器跳转到Web页面
     * @throws IOException
     */
    private void openBrowser() throws IOException {
        String url = "http://localhost:8086/api/admin/menu";
        try {
            String os = System.getProperty("os.name").toLowerCase();
            if (os.contains("win")) {
                // Windows系统
                Runtime.getRuntime().exec("cmd /c start " + url);
            } else {
                // 非Windows系统
                if (os.contains("mac")) {
                    // macOS系统
                    Runtime.getRuntime().exec("open " + url);
                } else {
                    // Linux系统
                    Runtime.getRuntime().exec("xdg-open " + url);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String readSqlFile(String file) throws IOException {
        // 加载资源
        Resource resource = resourceLoader.getResource(file);
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder sqlContent = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sqlContent.append(line).append("\n");
            }
            return sqlContent.toString();
        }
    }
}
